﻿using System.Linq;
using System.Collections.Specialized;
using Mvc.XForms.Utilities;

namespace Mvc.XForms.UI {
	public class LinqPagedList<T> : PagedList<T> {
		private readonly IQueryable<T> source;

		// Empty constructor so inherited objects can determine init order
		public LinqPagedList() { }

		public LinqPagedList(IQueryable<T> source, NameValueCollection collection, string pageIndexKey, int pageSize)
			: this(source, new PagedParameters(collection, pageIndexKey, pageSize)) { }

		public LinqPagedList(IQueryable<T> source, IPagedParameters gridParams) {
			this.source = source;
			InitWithParams(gridParams);
		}

		public LinqPagedList(IQueryable<T> source, int pageIndex, int pageSize) {
			this.source = source;
			Init(pageIndex, pageSize);
		}

		protected override int GetTotalCount() {
			var count = source.Count();
			return count;
		}

		protected override void ApplyPaging() {
			var pagedSource = source
				.Page(PageIndex, PageSize)
				.ToList();

			Items = pagedSource;
		}
	}
}